<template>
  <div class="container-box">
    <el-dialog title="商品列表" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false" width="80%">
      <el-table :data="list" stripe border highlight-current-row @row-dblclick="rowDblclick">
        <template v-for="(item, index) in dialogColums.filter(d => d.isTable)">
          <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable">
            <template slot-scope="scope">
              <div class="">{{ handleRowResult(item, scope.row) }}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsIndex, goodsAdd, updateAttrConfig } from '../../api/goods';
import { customerAdd, customerDetail } from '../../api/customer';
import curde from '@/mixins/curde'

export default {
  name: 'GoodsDialog',
  mixins: [curde],
  props: {
    id: {
      type: String,
      default: ''
    },
    operateType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogColums: [
        { title: '仓库', key: 'store_house_id', type: 'text', clearable: true, isFilter: true, isTable: false, isForm: false },
        { title: '商品名称', key: 'goods_name', type: 'text', clearable: true, isFilter: true, isTable: false, isForm: true },
        { title: '商品全称', key: 'full_goods_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '分类名称', key: 'cat_id', type: 'goodsCategoryDict', clearable: true, isFilter: false, isTable: false, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: false, isForm: true },
        { title: '基本&辅助单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false },
        { title: '单位换算', key: 'unit_convert', type: 'text', isFilter: false, isTable: false },
        { title: '基本单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位', key: 'unit_name2', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '基本单位换算', key: 'unit_convert', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位换算', key: 'unit_convert2', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '库存', key: 'stock', type: 'text', isFilter: true, isTable: true }
      ],
      list: [],
      saving: false,
      dialogVisible: false,
      rules: {
        company_name: [
          { required: true, message: '请输入单位名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品全称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        customer_name: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        area: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        company_type: [{ required: true, message: '请选择企业类型', trigger: ['change', 'blur'] }]
      },
      // dialogForm: {
      //   area: '广东省 广州市',
      //   area_address: '天健广场',
      //   bank: '123123',
      //   bank_name: '中国银行',
      //   company_name: '单位全称',
      //   full_company_name: '单位简称',
      //   company_type: '1',
      //   customer_name: '林',
      //   customer_type: '1',
      //   phone: '13812312312',
      //   remarks: '备注',
      //   status: '1',
      //   tel_phone: '020123123'
      // },
      dialogForm: {
        area: '',
        area_address: '',
        bank: '',
        bank_name: '',
        company_name: '',
        full_company_name: '',
        company_type: '',
        customer_name: '',
        customer_type: '1',
        phone: '',
        remarks: '',
        status: '1',
        tel_phone: ''
      }
    };
  },
  computed: {
    storeHouseDict() {
      return this.$store.getters.storeHouseDict;
    }
  },
  watch: {
    id(val) {
      if (val) {
        this.getDetail(val);
      }
    }
  },
  created() {
    this.getData();
  },
  methods: {
    rowDblclick(row, column, event) {
      this.$emit('callback', 'rowDblclick', row);
    },
    // 显示弹框
    showDialog(operateType, params) {
      this.dialogVisible = true;
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false;
    },
    // 获取商品数据
    async getData() {
      const { data } = await goodsIndex();
      this.allList = data?.list || [];
      this.handleSpreadList();
      // this.list = data?.list || [];
    },
    // 把商品数据中的规格展开；
    handleSpreadList() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        // 判断商品单规格 ｜ 多规格
        let attrConfig = [];
        if (d?.attrConfig?.config) {
          attrConfig = JSON.parse(d?.attrConfig?.config || '[]')
        }
        // 多规格
        if (attrConfig.length > 0) {
          const goodsItem = attrConfig.map(attr => {
            // socketData[`${d.id}_${attr.sku}`] = attr
            const attrItem = Object.assign(d, { attrConfigValue: attr });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 展示符合条件的数据
    handleList() {
      this.list = this.filterData(this.spreadList, this.createPayload(this.query))
      this.paging.total = this.list.length;
    },

    async getDetail(id) {
      const res = await customerDetail({ id: id || this.id });
      console.log('customerDetail--res==', res);
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return;
      // this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        payload.full_company_name = payload.company_name;
        const res = await customerAdd(payload);
        // console.log('customerAdd--res==', res);
        if (res.data) {
          if (res.data?.code < 0) {
            this.$message({ message: res.data?.msg || '操作失败', type: 'error' })
          }
          else {
            this.closeDialog();
            this.$message({ message: '添加成功', type: 'success' })
            this.$emit('callback', true, res.data);
          }
        }
        else {
          this.$message({ message: res?.msg || '操作失败', type: 'error' })
        }

        // this.$emit(true, { ...res });
        // if (data && data.length === 2) {
        //   if (data[1]) {
        //     this.getData();
        //     this.$message.success('添加成功')
        //     this.dialogVisible = false;
        //   }
        //   else {
        //     this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
        //   }
        // }
        // else {
        //   this.$message.error(`异常：添加失败`)
        // }
      }
      catch (e) {
        console.log('customerAdd--e==', e);
      }
      this.saving = false;
    },
    // 处理table 单元格显示；
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row, this.storeHouseDict);
      const value = row[item.key] || '';
      if (item.key === 'goods_name' || item.key === 'full_goods_name') {
        const sku = row.attrConfigValue && row.attrConfigValue.sku ? row.attrConfigValue.sku : '';
        return value + sku;
      }
      if (item.key === 'stock') {
        const sku = row?.attrConfigValue?.sku;
        if (sku && row?.attrValue && row?.attrValue.length > 0) {
          const skus = row?.attrValue.filter(d => d.sku === sku);
          if (!skus || skus.length === 0) {
            return ''
          }
          return skus.map(d => {
            let skuValue = '';
            if (d.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
              const unitNum = d.stock % row.unit_convert2;
              const unitNum2 = Math.floor(d.stock / row.unit_convert2);
              skuValue = `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
            }
            else {
              skuValue = `${d.stock}${row.unit_name}`
            }
            return (`${this.storeHouseDict[d.store_house_id].store_house_name}: ${skuValue}`)
          }).join('\n')
        }

        // const socketKey = `${d.id}_${attr.store_house_id}_${attr.sku}`
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      // if (item.key === 'cat_id') {
      //   const category = this.goodsCategoryDict[value]
      //   return category?.cat_name || value
      // }
      if (item.key === 'unit_name') {
        return `${row.unit_name} / ${row.unit_name2 || '-'}`
      }
      if (item.key === 'unit_convert') {
        if (row.unit_name2) {
          return `${row.unit_convert2}${row.unit_name} = ${row.unit_convert}${row.unit_name2}`
        }
        return
      }
      return value;
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}

.container-box {
  ::v-deep .el-table .cell {
    white-space: pre-line !important;
  }
  .el-pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
